<?php
/**
 * @File	  : base_model.php
 * @Project	  :
 * @author	  : ThanhMinh
 * @email	  : thanhminhld@yahoo.com - thanhminhld@gmail.com
 * @copyright : 2009
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Base_Model extends Model
{
	protected $_tbl = null;
	/**
	 * constructor function
	 */
	public function __construct()
	{
		parent::Model();
	}
    /**
     * @function
     *
     * @author Vo Thanh Minh <vothanhminh@kng-vn.com>
     * @access public
     * @param
     * @return void
     */
    public function optimize_Tbl()
    {
        $this->db->optimize_tbl($this->_tbl);
    }
	/**
	 * get_row
	 * @param array $where
	 * @return $result object
	 */
    public function get_row($where = null)
    {
        $result = null;
        $query = $this->db->get_where($this->_tbl, $where);
        if ($query->num_rows() > 0) {
            $result = $query->row_object();
        }
        return $result;
    }
	/**
	 * getTotalRows
	 *
	 * @author Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
	 * @access public
	 * @param  array
	 * @param  string
	 * @return int
	 */
    public function getTotalRows($arrWhere = array(), $field_groupby = '')
    {
	    if (count($arrWhere) > 0) {
            $this->db->where($arrWhere);
        }
        if (!empty($field_groupby) && is_string($field_groupby)) {
            if ($this->db->field_exists($field_groupby, $this->_tbl)) {
                $this->db->group_by($field_groupby);
            }
        }
		$query = $this->db->get_where($this->_tbl, $arrWhere);

		return $query->num_rows();
    }	
	/**
	 * @function loadList
	 *
	 * @author 	 Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
	 * @access 	 public
	 * @param	 array
	 * @param	 int
	 * @param	 int
	 * @param	 string
	 * @param	 string
	 * @return 	 array
	 */
	public function loadList($arrWhere = array(), $limit = 10, $offset = 0, $order = '', $mode = '')
	{
	    if (is_string($order) && strlen($order) > 0) {
	        if ( ! preg_match('/(asc|ASC|desc|DESC)/', $mode)) {
                $mode = 'asc';
	        }
	        $this->db->order_by($order, $mode);
	    }

        if ($limit == 'all') {
            $query = $this->db->get_where($this->_tbl, $arrWhere);
        } else {
            $query = $this->db->get_where($this->_tbl, $arrWhere, $limit, $offset);
        }
        $arrList = array();
        if ($query->num_rows() > 0) {
            foreach($query->result() as $row) {
                $arrList[] = $row;
            }
        }
		return $arrList;
	}	
    /**
     * store
     * @access public
     * @param
     * @return
     */
    public function store($data, $primary_field, $multiLang=true, $fUpdate=false)
    {
        /**
         * Truong hop ordering nay cho insert record moi
         */
        $ordering_field = '';
    	if ($this->db->field_exists('ordering', $this->_tbl) && $fUpdate==false) {
    	    $ordering_field = 'ordering';
    		// Tao cau select
    		$this->db->select_max('ordering');
    		// query cau select
    		$query = $this->db->get($this->_tbl);
    		// Lay doi tuong sau khi query
    		$ordObj = $query->row_object();
    		// assign gia tri cho field
    		$row_insert['ordering'] = $ordObj->ordering + 1;
    	}
        /**
         * Truong hop $primary_field nay cho insert record moi
         */
    	if ($this->db->field_exists($primary_field, $this->_tbl)) {

    		$this->db->select_max($primary_field);
    		$query = $this->db->get($this->_tbl);
    		$priObj = $query->row_object();
    		$row_insert[$primary_field] = $priObj->$primary_field + 1;
    	}
		// select * from vnc_lang
		$query = $this->db->get('lang');
		// Lay list Lang
		$langList = $query->result_object();

		// new language id
		$newLangId = '';
	    if (array_key_exists($primary_field, $data) && is_numeric($data[$primary_field])
	        && $data[$primary_field] > 0) {
            $this->db->where(array($primary_field => $data[$primary_field]));
            $arrLangId = array();
            foreach($langList as $lang) {
                array_push($arrLangId, $lang->id);
            }
            if (!empty($ordering_field)) {
                $ordering_field = ', ' . $ordering_field;
            }
            $this->db->where_in('lang_id', $arrLangId);
            $this->db->select('lang_id' . $ordering_field);
            $this->db->from($this->_tbl);
            // $resultObj is instanceof CI_DB_mysql_result
            $resultObj = $this->db->get();
            if (count($arrLangId) > $resultObj->num_rows) {
                $recordTbl = array();
                foreach ($resultObj->result() as $row) {
                    array_push($recordTbl, $row->lang_id);
                    if (!empty($ordering_field)) {
                        $row_insert['ordering'] = $row->ordering;
                    }
                }
                $arrDiff = array_values(array_diff($arrLangId, $recordTbl));
                $newLangId = $arrDiff[0];
            }
	    }
		foreach($langList as $lang) {
			$row_insert['lang_id'] = $lang->id;
			foreach($data as $field=>$value) {
				if (is_array($value)) {
					$row_insert[$field] = trim($value[$lang->id]);
				} else {
					$row_insert[$field] = trim($value);
				}
			}
			if (!$fUpdate) {
				// insert du lieu
				$ret = $this->db->insert($this->_tbl, $row_insert);
			} else {
			    if ($newLangId == $lang->id) {
			        // Insert. Truong hop nay them moi record khi them mot ngon ngu moi
                    $ret = $this->db->insert($this->_tbl, $row_insert);
			    } else {
					// update
					$arrWhere = array($primary_field => $data[$primary_field],
									  'lang_id'		 => $lang->id);
			  		$this->db->where($arrWhere);
					//print_r($row_insert);
					$ret = $this->db->update($this->_tbl, $row_insert);
			    }
			}
			if ($ret == FALSE) {
			    break;
			}
		}

    	return $ret;
    }
	/**
	 * storeTblWithoutLang
	 * @access public
	 *
	 */
	public function storeTblWithoutLang ($data, $primary_field, $fUpdate=false)
	{
        if (!is_array($data)) {
            return FALSE;
        }
        $row_insert = array();
		if ($this->db->field_exists($primary_field, $this->_tbl)) {
    		$this->db->select_max($primary_field);
    		$query = $this->db->get($this->_tbl);
    		$priObj = $query->row_object();
    		$row_insert[$primary_field] = $priObj->$primary_field + 1;
    	}

        foreach ($data as $key => $value) {
            if (!$this->db->field_exists($key, $this->_tbl)) {
                return FALSE;
            }
            $row_insert[$key] = $value;
        }

	    if (!$fUpdate) {
			// insert du lieu
			$ret = $this->db->insert($this->_tbl, $row_insert);
		} else {
			// update
			$arrWhere = array($primary_field => $data[$primary_field]);
			$this->db->where($arrWhere);
			//print_r($row_insert);
			$ret = $this->db->update($this->_tbl, $row_insert);
		}

		return $ret;
	}
	/**
	 * deleteTbl
	 *
	 * @access public
	 * @author Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
	 *
	 */
	public function deleteTbl($arrWhere = array(), $primary_field, $delWhereIn = false, $fieldWhereIn = '')
	{
	    $errMsg = '';
	    if (!$this->db->field_exists($primary_field, $this->_tbl)) {
	        $errMsg = 'primary field not exist';
	        return $errMsg;
	    }
	    if (!is_array($arrWhere) || count($arrWhere) <= 0) {
	        $errMsg = 'The condition where not found';
	        return $errMsg;
	    }
	    if ($delWhereIn == true && strlen($fieldWhereIn) > 0) {
	        $this->db->where_in($fieldWhereIn, $arrWhere);
	        $ret = $this->db->delete($this->_tbl);
	    } else {
	        $ret = $this->db->delete($this->_tbl, $arrWhere);
	    }
	    $this->optimize_Tbl();

	    return $ret;
	}
	/**
	 * loadListWhereIn
	 *
	 * @access	: public
	 * @author	: Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
	 * @param	: string $field_sel
	 * @param	: sring $fieldWhereIn
	 * @param	: string or array $arrWhereIn
	 *
	 * @return	: NULL or FALSE or array
	 */
	public function loadListWhereIn($field_sel, $fieldWhereIn = '', $arrWhereIn = '', $otherConditionWhere = array())
	{
	    $strField = '';
	    $this->db->distinct();
	    if (is_array($field_sel) && count($field_sel) > 0) {
	        $strField = implode(',', $field_sel);
	        $this->db->select($strField);
	    } else if (is_string($strField) && strlen($strField) > 0) {
	        $this->db->select($strField);
	    }
	    if (!is_string($fieldWhereIn) || strlen($fieldWhereIn) <= 0) {
	        return FALSE;
	    }
	    if (is_array($arrWhereIn) && count($arrWhereIn) > 0) {
	        $this->db->where_in($fieldWhereIn, $arrWhereIn);

	    } else if (is_string($arrWhereIn) && strlen($arrWhereIn) > 0) {
	        $this->db->where($fieldWhereIn, $arrWhereIn);
	    } else {
	        return FALSE;
	    }
	    if (is_array($otherConditionWhere) && count($otherConditionWhere) > 0) {
	        $this->db->where($otherConditionWhere);
	    }
	    $query = $this->db->get($this->_tbl);

        if (!is_object($query)) {
            return NULL;
        }
        $arrist = array();
		if ($query->num_rows() > 0) {
			foreach($query->result() as $row) {

				$arrist[] = $row;
			}
		}
        return $arrist;
	}
}
?>